<?php

//
// +---------------------------------------------------------+
// | 开发组
// +---------------------------------------------------------+
// | Copyrigh  (c)  2020 The PHP Group
// +---------------------------------------------------------+
// | 商户 代理商
// +---------------------------------------------------------+
// | zxc
// | php后端开发
// |
// +———————————————————+
//

namespace App\Models\Api;

use App\Tools\Financial;
use App\Tools\Prstatic;
use Illuminate\Database\Eloquent\Model;

class StoreCart extends Model
{

    protected $table = 'store_cart';
    protected $primaryKey = 'id';
    protected $dateFormat = 'U'; // 时间戳

    /**
     * 获取订单确认页选中的商品
     * @param $ids
     * @param $store_id
     * @param int $type
     * @return array|array[]
     */
    public static function getListByIds($ids, $store_id)
    {
        $list = self::from('store_cart as s')
            ->select(['s.id', 's.is_give', 's.type', 's.goods_id', 's.goods_num', 'g.goods_name', 'g.goods_img', 'gs.sale_price', 'gs.buy_num', 'gs.get_num'])
            ->leftJoin('goods as g', 'g.id', '=', 's.goods_id')
            ->leftJoin('goods_store as gs', 'gs.goods_id', '=', 's.goods_id')
            ->where(['s.store_id' => $store_id, 'gs.store_id' => $store_id, 'g.status' => 1])
            ->whereIn('s.id', $ids)
            ->get()->toArray();
        if ($list) {
            $dan = [];
            $zeng = [];
            $pids = [];
            $money = 0;
            $num = 0;
            $pay_num = 0;
            foreach ($list as $key => $item) {
                $num += $item['goods_num'];
                if ($item['is_give'] == 1) {
                    $zeng[] = $item;
                } elseif ($item['type'] == 1) {
                    $pay_num += $item['goods_num'];
                    $money += $item['goods_num'] * $item['sale_price'];
                    $dan[] = $item;
                    if (($item['goods_num'] > $item['buy_num']) && ($item['get_num'] > $item['buy_num'])) {
                        $item['is_give'] = 1;
                        $item['goods_num'] = intval($item['goods_num'] / $item['buy_num']) * $item['get_num'];
                        $zeng[] = $item;
                    }
                } else {
                    $pids[] = $item['id'];
                }
            }
            if ($pids) {
                $listA = self::from('store_cart as s')
                    ->select(['s.id', 's.is_give', 's.type', 's.goods_id', 's.goods_num', 'g.goods_name', 'g.goods_img', 'gs.sale_price'])
                    ->leftJoin('goods as g', 'g.id', '=', 's.goods_id')
                    ->leftJoin('goods_store as gs', 'gs.goods_id', '=', 's.goods_id')
                    ->where(['s.store_id' => $store_id, 'gs.store_id' => $store_id, 'g.status' => 1])
                    ->whereIn('s.goods_pid', $pids)
                    ->get()->toArray();
                if ($listA) {
                    foreach ($listA as $key => $item) {
                        if ($item['is_give'] == 1) {
                            $zeng[] = $item;
                        } else {
                            $pay_num += $item['goods_num'];
                            $money += $item['goods_num'] * $item['sale_price'];
                            $dan[] = $item;
                        }
                    }
                }
            }
            return ['zeng' => $zeng, 'dan' => $dan, 'money' => $money, 'num' => $num, 'pay_num' => $pay_num];
        }
        return [];
    }

    /**
     * 获取列表
     * @param $store_id
     * @return array
     */
    public static function getListBySid($store_id)
    {
        // 代发
        $is_agent = Store::where(['id' => $store_id])->value('is_agent');
        $list = self::from('store_cart as s')
            ->select([
                's.id', 's.goods_pid', 's.goods_id', 's.store_id', 's.goods_num', 's.is_give', 's.type', 'g.goods_group', 'c.cate_name',
                'g.goods_sn', 'g.goods_img', 'g.mini_quantity', 'g.goods_name', 'g.goods_price', 'gs.sale_price'
            ])
            ->leftJoin('goods as g', 'g.id', '=', 's.goods_id')
            ->leftJoin('goods_category as c', 'c.id', '=', 'g.cate_id')
            ->leftJoin('goods_store as gs', 'gs.goods_id', '=', 'g.id')
            ->where(['s.store_id' => $store_id, 'gs.store_id' => $store_id, 'g.status' => 1])
            ->orderBy('s.id')
            ->get()->toArray();
//        v(json_encode($list));die();
        $danArr = [];
//        $discountRate = \App\Models\Admin\Store::where(['id' => $store_id])->value('discount_rate') ?? 1;
        $goodTotal = 0;
        foreach ($list as $key => $item) {
            $item['mini_quantity'] = $is_agent == 1 ? 1 : $item['mini_quantity'];
            
            if ($item['type'] == 1) {
                // 单品：直接累加价格
                $goodTotal += $item['goods_num'] * $item['sale_price'];
                $danArr[] = $item;
            } elseif ($item['type'] == 2) {
                if ($item['goods_pid'] == 0) {
                    // 组合商品：只计算组合商品本身的价格，不计算子商品
                    $goodTotal += $item['goods_num'] * $item['sale_price'];
                    $danArr[] = self::makeArr($list, $item['id'], $item);
                }
                // 组合商品的子商品（goods_pid != 0）不在这里计算价格，避免重复计算
            }
        }
        return [$danArr, ["goodTotal"=>$goodTotal]];
    }

    public static function makeArr($list, $pid, $data)
    {
        $num = 0;
        $money = 0;
        $dataArr = [];
        $giftArr = [];
        // 获取折扣
        foreach ($list as $item) {
            if ($item['goods_pid'] == $pid) {
                if ($item['is_give'] == 0) {
                    $money += $item['goods_num'] * $item['sale_price'];
                    $dataArr[] = $item;
                } else {
                    $num += $item['goods_num'];
                    $giftArr[] = $item;
                }
            }
        }
        $data['goods_price'] = $money;
        $data['gift_num'] = $num;
        // 解析goods_group并添加number字段到对应商品
        $goodsGroup = json_decode($data['goods_group'], true);
        $groupMap = [];
        if (is_array($goodsGroup)) {
            foreach ($goodsGroup as $group) {
                $groupMap[$group['id']] = $group['number'];
            }
        }
        // 为group中的商品添加number字段
        foreach ($dataArr as &$item) {
            if (isset($groupMap[$item['goods_id']])) {
                $item['number'] = $groupMap[$item['goods_id']];
            }
        }
        $data['group'] = $dataArr;
        $data['gift'] = $giftArr;
        return $data;
    }

    /**
     * 添加购物车
     * @param $info
     * @return mixed
     */
    public static function addCart($info)
    {
        $time = time();
        $info['updated_at'] = $time;
        $info['created_at'] = $time;

        return self::insertGetId($info);
    }

    /**
     * 编辑购物车
     * @param $id
     * @param $info
     * @return mixed
     */
    public static function editCart($id, $info)
    {
        $info['updated_at'] = time();

        return self::where(['id' => $id])->update($info);
    }
}